
var Msales = {
    uPlaceOrderSubmit: '/tticar/placeOrderSubmit',
    editIndex: -1,
    isDg: 0,
    winThat: undefined,
    dgType: undefined,
    storeId :undefined,
    customerId:undefined,
    goodsArr : [],
    allIndex :0

};




Msales.dg = function () {

    $.ajax({
        type: "GET",
        url: "/mMateriel/materielListForPlaceOrder",
        dataType: "json",
        success: function (data) {
            Msales.goodsArr = data;
        }
    });

    Msales.dtable = $('#placeOrderGoods_table');
    Msales.dtable.datagrid({
        // pagination: true,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: true,
        scrollbarSize:0,
        nowrap:false,
        toolbar: [
            {
                text: '增加', iconCls: 'icon-add', handler: function () {

                    Msales.saveDgGoods();
                }
            },
            {
                text: '删除', iconCls: 'icon-remove', handler: function () {
                    Msales.remove();
                }
            }
        ],
        columns: [[
            {field: 'materielSkuId', checkbox: true},//规格id
            {field: 'id', title: '<span style="color:deeppink">品名规格</span>', width: 300, halign: 'center',
                // editor: {type: 'house'},
                editor: {
                type: 'combobox', options: {
                    mode: 'remote',
                    valueField: 'id',
                    textField: 'name',
                    nowrap:false,
                    url: "/mMateriel/materielListForPlaceOrder",
                    method:'get',
                    // onLoadSuccess: function () { //加载完成后,设置选中第一项
                    //     var val = $(this).combobox('getData');
                    //     for (var item in val[0]) {
                    //         if (item == 'id') {
                    //             $(this).combobox('select', val[0][item]);
                    //         }
                    //     }
                    // }
                    //     onChange: function (value,row) {
                    //         $('#goodsAndSkusId').val(value);
                    //     },
                }
            },  formatter: function (value, row, index) {
                for (var i = 0; i < Msales.goodsArr.length; i++) {
                    if (value == Msales.goodsArr[i].id) {
                        return Msales.goodsArr[i].name;
                    }
                }
                return value;
            }
            },
            {field: 'count', title: '<span style="color:deeppink">数量</span>', width: 60, halign: 'center',
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'unitPrice', title: '<span style="color:deeppink">单价</span>', width: 60, halign: 'center', formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                },
                editor: {type: 'numberbox', options: {required: true, min: 0, precision: 2}}
            },
            // {
            //     field: 'transportFee', title: '运费', width: 60, halign: 'center', formatter: function (value, row, index) {
            //     return Number(value).toFixed(2);
            // }
            // },

            // {field: 'invName', title: '关联的存货', halign: 'center', width: 260},
            {field: 'repositoryCount', title: '存货库存',  halign: 'center',width:80},
            {field: 'storeId', title: 'storeId', width:100,hidden:true},
            {field: 'customerId', title: 'customerId', width:100,hidden:true},
            {field: 'goodsName', title: 'goodsName', width:100,hidden:true},
            {field: 'skuName', title: 'skuName', width:100,hidden:true},
            {field: 'needInv', title: 'needInv', width:100,hidden:true},

        ]],
        onClickCell: function (index, field) {
            if (Msales.editIndex != index) {
                if (Msales.editIndex > -1) {
                    Msales.dtable.datagrid('endEdit', Msales.editIndex);
                }
                Msales.editIndex = index;
            }
  
            if (field == "id" || field == "count" || field == "unitPrice") {
                Msales.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            Msales.haha(index, row, changes)

        }



    });

    Msales.dtable.datagrid('enableCellEditing');

    //mark2


};

Msales.refresh = function () {
    window.location.reload();
};

Msales.caculate = function () {
    var rows = Msales.dtable.datagrid("getData").rows;
    var goodsFee = 0;
    var totalNUm = 0;

    for (var i = 0; i < rows.length; i++) {
        goodsFee = Number(goodsFee) + Number(rows[i].unitPrice) * Number(rows[i].count);
        totalNUm = Number(totalNUm) + Number(rows[i].count);
    }
    $("#totalNum").numberbox("setValue", totalNUm);
    // $("#totalFee").numberbox("setValue", goodsFee);
    $("#totalFee").numberbox("setValue", goodsFee);

};

Msales.isExist = function (rows, skusId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skusId == skusId) {
            return true;
        }
    }
    return false;
};
Msales.saveDgGoods = function () {

    document.onkeydown = Msales.keyDown;

    Msales.storeId = $('#ttstoreId').combobox('getValue');
    if (Msales.storeId == null || Msales.storeId == undefined || Msales.storeId == '') {
        $yd.alert("请先选择下单店铺")
        return false;
    }
    
    Msales.customerId = $('#custom').combobox('getValue');
    if (Msales.customerId == null || Msales.customerId == undefined || Msales.customerId == '') {
        $yd.alert("请先选择客户信息")
        return false;
    }
    var rows = Msales.dtable.datagrid("getRows");//mark11111
    var row = rows[rows.length -1];
    Msales.allIndex = rows.length-1;
    if (rows.length >0) {
        Msales.dtable.datagrid('endEdit', rows.length - 1);

        Msales.haha(rows.length-1, row, true);


}


    Msales.dg();
    var rows = Msales.dtable.datagrid("getData").rows;

            Msales.dtable.datagrid('appendRow', {
                id:":",
                storeId: Msales.storeId,
                customId:Msales.customerId,
                materielSkuId: null,
                goodsName: null,
                count: 1,
                unitPrice: null,
                repositoryCount: null,

            }).datagrid('clearSelections');

    Msales.caculate();

    Msales.isDg = 0;
    Msales.winThat = undefined;
    Msales.dgType = undefined;

    var list = $(":checkbox");
    var tmp = 0;
    for (var i = 1; i < list.length; i++) {
        var td = $(list[i]).closest("td");
        if (td.hasClass("datagrid-row-selected")) {
            tmp = i;
        }
    }
    if (tmp == 0) {
        $(list[1]).closest("td").trigger("click");
    }

    $(":checkbox").attr("tabindex", -1);
};

Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
Msales.remove = function () {
    var sels = Msales.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['id']);
    });

    $.each(ids, function (i, n) {
        var rows = Msales.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].id == n) {
                Msales.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });
    Msales.caculate();

    var tds = $(".datagrid-row-selected");
    if (tds.length == 0) {
        var checks = $(":checkbox");
        if (checks.length > 1) {
            $(checks[1]).closest("td").trigger("click");
        }
    }
};

//全删除
Msales.deleteAll = function () {
    var rows = Msales.dtable.datagrid('getRows');
    for (var i=rows.length;i>0;i--) {
            Msales.dtable.datagrid('deleteRow', i-1);
    }
    Msales.caculate();
};

Msales.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
// Msales.save0 = function () {
//     Msales.save(0);
// };
// Msales.save1 = function () {
//     Msales.save(1);
// };
Msales.save = function () {
    //结束编辑状态
    //mark3

    var rows = Msales.dtable.datagrid("getRows");//mark11111
    var row = rows[rows.length -1];

    if (rows.length >0) {
        Msales.dtable.datagrid('endEdit', rows.length - 1);


        Msales.haha(rows.length - 1, row, true);
    }




    $('#placeOrderForm').form('submit', {
        url: Msales.uPlaceOrderSubmit,
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = Msales.dtable.datagrid("getRows");

            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            for (var i =0; i<rows.length;i++) {
                if (rows[i]['needInv']!=1 && (rows[i]['repositoryCount']< rows[i]['count'])){
                    $yd.alert("第"+(i+1)+"行库存只剩"+rows[i]['repositoryCount']+"，小于下单量"+rows[i]['count']+"。")
                    return false;
                }

            }


            //封装数据
            $("#placeOrderMessage").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }else {
                $yd.alert(d.message)
            }
        }

    });
};


Msales.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
};
Msales.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if (e.keyCode == 13 && Msales.dgType == "goods") {
        Msales.saveDgGoods();
    } else if (e.keyCode == 13 && Msales.dgType == "house") {
        Msales.saveDgHouse();
    }
    if (Msales.isDg != 0 && e.keyCode == 27 && Msales.winThat) {//ESC
        Msales.winThat.close();
    }
    if (Msales.isDg == 0) {
        if (e.keyCode == 45) {//insert
            Msales.plus();
        }
        if (e.keyCode == 46) {//del
            Msales.remove();
        }
        if (e.keyCode == 32) {//space
            var tds = $(".datagrid-row-selected");
            if (tds.length > 0) {
                var check = $(tds).find(":checkbox")[0];
                $(check).trigger("click");
            }
        }
        // if (e.shiftKey && e.keyCode == 83) {
        //     Msales.save(1);//生单入库：Shfit + A
        // }
        // if (e.shiftKey && e.keyCode == 65) {
        //     Msales.save(0);//生单: Shift + S
        // }
        if (e.shiftKey && e.keyCode == 82) {
            Msales.refresh();
        }
    }
};
Msales.init = function () {
    
    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = Msales.mouseClick;

    //快捷键
    document.onkeydown = Msales.keyDown;
    document.onkeyup = Msales.keyUp;

    // setTimeout("$('#orderTime').focus()", 500);
    $("a").attr("tabindex", -1);
    $(":checkbox").attr("tabindex", -1);
};
Msales.mouseClick = function (e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (Msales.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (Msales.editIndex != -1) {
            Msales.dtable.datagrid('endEdit', Msales.editIndex);
            Msales.editIndex = -1;
            Msales.caculate();
        }
    }
};
$(function () {
    Msales.obtn = '#mSales_btn';
    Msales.dg(); // 数据表格
    // Msales.btn(); // 初始化按钮
    Msales.init(); // 数据表格
    
    //初始化店铺下拉框
    $("#ttstoreId").combobox({
        url: "/wStore/select",
        type:'get',
        valueField:'id',
        textField:'name',
        async:false,
        onChange: function () {
            Msales.deleteAll();
            Msales.custom();
            $('#customAddr').combobox('setValue', '');
        },
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox('getData');
            for (var item in val[0]) {
                if (item == 'id') {
                    $(this).combobox('select', val[0][item]);
                }
            }
            // Msales.custom();
        }
    });
    //初始化客户下拉框
    // $("#custom").combobox({
    //     url: "/tticar/customerList?storeId=" +$("#ttstoreId").val(),
    //     mode:'remote',
    //     valueField:'id',
    //     textField:'name',
    //     method :'get',
    //     async:false,
    //     onChange: function () { //改变选择事件
    //         // var val = $(this).combobox('getData');
    //         // for (var item in val[0]) {
    //         //     if (item == 'id') {
    //         //         $(this).combobox('select', val[0][item]);
    //         //     }
    //         // }
    //         Msales.deleteAll();
    //     }
    //
    //
    //
    // });


});
Msales.custom = function () {
    $("#custom").combobox({
        url: "/tticar/customerList?storeId=" +$("#ttstoreId").combobox('getValues'),
        mode:'remote',
        valueField:'storeId',
        textField:'storeName',
        method :'get',
        async:false,
        onChange: function () { //改变选择事件
            // var val = $(this).combobox('getData');
            // for (var item in val[0]) {
            //     if (item == 'id') {
            //         $(this).combobox('select', val[0][item]);
            //     }
            // }
            Msales.deleteAll();
            Msales.address();
        }



    });
}
Msales.address = function () {
    $("#customAddr").combobox({
        url: "/tticar/getAddr?storeId=" +$("#custom").combobox('getValues'),
        valueField:'id',
        textField:'addr',
        async:false,
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox('getData');
            for (var item in val[0]) {
                if (item == 'id') {
                    $(this).combobox('select', val[0][item]);
                }
            }
            // Msales.custom();
        }
    });
};
Msales.haha = function ( index,row,changes) {
    var repositoryCountData = 0;
    var unitPriceData = 0;
    a();
    function a() {
        // var value = row['id']
        // var value = $('#goodsAndSkusId').val();
        // console.log(value)
        // console.log(11111111111)
        var rows = Msales.dtable.datagrid("getRows");
        $("#rows").val(JSON.stringify(rows));
        // if (value != null && value != ''){
        //     var goodsId = value.split(',')[0];
        //     var skuId = value.split(',')[1];
            $.ajax({
                url:'/mMateriel/getDetailsByRows',
                // '?tticarGoodsId='
                // +goodsId+'&skuValue='+skuId+'&customId='+$("#custom").combobox('getValue')+'&rows='+$('#rows').val()
                // +'&addrId='+$("#customAddr").combobox('getValue')+'&sellStoreId='+$("#ttstoreId").combobox('getValue'),
                type:'post',
                data :{
                    // tticarGoodsId:goodsId,
                    // skuValue:skuId,
                    // customId:$("#custom").combobox('getValue'),
                    rows:$('#rows').val(),
                    // addrId:$("#customAddr").combobox('getValue'),
                    // sellStoreId:$("#ttstoreId").combobox('getValue')
                },
                async:false,
                success:function (data) {
                    
                    for (var i =0;i< data.length; i++){
                        var repositoryCountData = 0;
                        var unitPriceData = 0;
                        var goodsName = "";
                        var skuName = "";
                        var needInvData = 0;
                        repositoryCountData=data[i].count;
                        unitPriceData=data[i].unitPrice;
                        goodsName=data[i].goodsName;
                        skuName=data[i].skuName;
                        needInvData=data[i].needInv;

                     var row =  Msales.dtable.datagrid('getData').rows[i];
                        if (row['unitPrice'] < 0.01) {
                            Msales.dtable.datagrid('updateRow', {

                                index: i ,
                                row: {
                                    repositoryCount: repositoryCountData,
                                    unitPrice:unitPriceData,
                                    goodsName :goodsName,
                                    skuName:skuName,
                                    needInv:needInvData
                                }
                            });
                        }else {
                            Msales.dtable.datagrid('updateRow', {

                                index: i ,
                                row: {
                                    repositoryCount: repositoryCountData,
                                    goodsName :goodsName,
                                    skuName:skuName,
                                    needInv:needInvData
                                }
                            });
                        }


                    }

                    Msales.caculate();

                }
            });
        // }


    };


        // Msales.caculate();

}

//重置按钮
var resetBtn = document.getElementById("resetButton");
resetBtn.addEventListener("click", function() {
    $("#ttstoreId").combobox("setValue", "");
    $("#custom").combobox("setValue", "");
    $("#customAddr").combobox("setValue", "");
});
//保存按钮
var resetBtn = document.getElementById("saveButton");
resetBtn.addEventListener("click", function() {
    Msales.save();
});
